package sendcloud

import (
	"net/smtp"
	"strconv"
	"strings"
)

type Message struct {
	To       string
	Subject  string
	Body     string
	MimeType string
	Cc       string
}

func NewMessage(to, subject, body, mime string) *Message {
	return &Message{To: to, Subject: subject, Body: body, MimeType: mime}
}

func (self *Message) SetHeaderCc(cc string) *Message {
	self.Cc = cc
	return self
}

type Mailer struct {
	Host     string
	Port     int
	UserName string
	PassWord string
	FromMail string
	FromName string
}

func NewMailer(host, user, password string, port int) *Mailer {
	return &Mailer{Host: host, Port: port, UserName: user, PassWord: password}
}

func (self *Mailer) SetFrom(fromMail, fromName string) *Mailer {
	self.FromMail = fromMail
	self.FromName = fromName
	return self
}

func (self *Mailer) DialAndSend(msg *Message, auth smtp.Auth) error {
	if auth == nil {
		auth = NewAuth(self.UserName, self.PassWord)
	}
	msgStr := "To: " + msg.To + "\r\n"
	if msg.Cc != "" {
		msgStr += "Cc: " + msg.Cc + "\r\n"
	}
	if self.FromName == "" {
		self.FromName = self.FromMail
	}
	msgStr += "From: " + self.FromName + "<" + self.FromMail + ">\r\n"
	msgStr += "Subject: " + msg.Subject + "\r\n"
	msgStr += "Content-Type: " + msg.MimeType + ";charset=UTF-8\r\n\r\n"
	msgStr += msg.Body
	addr := self.Host + ":" + strconv.Itoa(self.Port)
	sendTos := strings.Split(msg.To, ";")
	err := smtp.SendMail(addr, auth, self.FromMail, sendTos, []byte(msgStr))
	return err
}
